var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');
var openId = wx.getStorageSync('openId');
var detailList = "";
var list = new Array();
var start = 0;
var length = 10;
var sign = "0";
var util = require('../../../utils/util.js');
var leftTime = new Array();
var cOrderNo = "";
var goodOrders = new Array();
var deliveryFee = 0;
var receiveName = "";
var receivePhone = "";
var orderNo = "";
var json = "";
var types = "";
var phone = "";
var alertMsg = new Array();
var createTime = null;
var showTime = true;
var limitTime = "";
var deliveryLimitTime = "";
var flag = "";
var onemoreFlag = false;
var app = getApp();
Page({
  /**
  * 页面的初始数据
  */
  data: {
    hiddenLoading: true,    //loading
    alertModel: false
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
    if (flag == "list") {
      wx.redirectTo({
        url: '/pages/userOrder/userOrderList/userOrderList'
      })
    }
    if (flag == "index") {
      wx.switchTab({
        url: '/pages/index/index'
      })
    }

  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {

    var that = this;
    
    that.setData({
      yunId: yunId,
      openId: openId
    })
    that.orderDetail();
    // that.searchOrder(event);

  },
  pay:function(e){
    var flags = "list";
    alertMsg = new Array();
    var orderNo = e.currentTarget.dataset.reforderno;
    var payTyime = util.formatTime(new Date()).toString();
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    // console.log("%%%%%%%%")
    // console.log(orderNo, openId, yunId)
    wx.request({
      url: apiHost + 'xcx/order/notPaySubmit',
      data: {
        openId: openId,
        yunId: yunId,
        orderNo: orderNo
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (result) {
        // console.log("!!!!");
        // console.log(result)
        /**
       * 获取系统信息
       */
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              hiddenLoading: true
            });
          }
        });
        // console.log(result)
        if (result.data.code == "10000") {
          var timeStamp = result.data.data.timeStamp
          var nonceStr = result.data.data.nonceStr
          var packages = result.data.data.package
          var paySign = result.data.data.paySign
          var signType = result.data.data.signType
          var appId = result.data.data.appId
          orderNo = result.data.data.orderNo;
          //调支付接口
          wx.requestPayment({
            appId: appId,
            timeStamp: timeStamp,
            nonceStr: nonceStr,
            'package': packages,
            signType: signType,
            paySign: paySign,
            'success': function (res) {
              // console.log(res);
              //下单成功后跳转到订单详情页
              wx.navigateTo({
                url: '/pages/userOrder/orderDetail/orderDetail?orderNo=' + orderNo + "&yunId=" + yunId + "&openId=" + openId + "&flag=" + flags,
              })
            },
            'fail': function (res) {
            }
          })
        } else {
          alertMsg.push(result.data.msg);
          that.setData({
            alertModel: true,
            alertMsg: alertMsg
          })
        }
        if (result.data.code == "10098") {
          alertMsg.push("商品库存不足！");
          that.setData({
            alertModel: true
          })
        }
        that.setData({
          alertMsg: alertMsg
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  //下拉刷新
  onPullDownRefresh: function () {
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    that.onLoad()
    /**
        * 获取系统信息
        */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          hiddenLoading: true
        });
      }
    });
  },
  // 页面渲染完成后 调用  
  onReady: function () {
    var flags = true;
    if(flags){
      var interval = setInterval(function () {
        flags = false;
        var that = this;
        leftTime = new Array();
        var nowTime = util.formatTime(new Date()).toString();
        var Nhour = nowTime.substring(11, 13) * 1;
        var Nmin = nowTime.substring(14, 16) * 1;
        var Nsec = nowTime.substring(17, 19) * 1;
        types = "2";
        for (var i = 0; i < list.length; i++) {
          
          if (list[i].state == "1") {
            var payTime = list[i].payTime;
            orderNo = list[i].orderNo;
            var createtime = list[i].createTime;
            if (list[i].payType == "0") {
              var Emin = createtime.substring(14, 16) * 1 + limitTime * 1;
              var Ehour = createtime.substring(11, 13) * 1;
              var Esec = createtime.substring(17, 19) * 1;
            } else {
              var Emin = payTime.substring(14, 16) * 1 + limitTime * 1;
              var Ehour = payTime.substring(11, 13) * 1;
              var Esec = payTime.substring(17, 19) * 1;
            }
            if (Emin > 60) {
              Emin = Emin - 60;
              Ehour = Ehour + 1;
            }
            var Lmin = 0;
            var Lsec = 0;
            var Lhour = 0;
            if (Esec >= Nsec) {
              Lsec = Esec - Nsec;
            } else {
              Esec = Esec + 60;
              Lsec = Esec - Nsec;
              Emin = Emin - 1;
            }
            if (Emin >= Nmin) {
              Lmin = Emin - Nmin;
            } else {
              Emin = Emin + 60;
              Lmin = Emin - Nmin;
              Ehour = Ehour - 1;
            }
            Lhour = Ehour - Nhour;
            //当前时间是否大于过期时间判断
            var flags = false;
            if (Nhour > Ehour) {
              flags = true;
            }
            if (Nhour == Ehour) {
              if (Nmin > Emin) {
                flags = true;
              }
              else if (Nmin == Emin) {
                if (Nsec > Esec) {
                  flags = true;
                }
              }
            }
            if ((Lmin == 0 && Lsec == 0) || flags) {
              wx.request({
                url: apiHost + 'xcx/order/confirmAcceptOrder',
                data: {
                  yunId: yunId,
                  openId: openId,
                  orderNo: orderNo,
                  state: '0',
                  'type': types
                },
                header: {
                  'conttent-type': 'application-json'
                },
                success: function (res) {
                  console.log("333333");
                  that.orderDetail();
                }
              })
            }
            if (Lmin < limitTime * 1) {
              if (Lmin < 10 || Lsec < 10) {
                if (Lmin < 10) {
                  Lmin = "0" + Lmin;
                }
                if (Lsec < 10) {
                  Lsec = "0" + Lsec;
                }
              }
              leftTime.push("00:" + Lmin + ":" + Lsec);
            }
          } else {
            leftTime.push("");
          }

        }
        that.setData({
          leftTime: leftTime
        })
      }.bind(this), 1000);
    }
    
  },
  contact: function (event) {
    var phone = event.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone //仅为示例，并非真实的电话号码
    })
  },
  //评价
  judg: function (e) {
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    orderNo = e.currentTarget.dataset.reforderno;
    wx.navigateTo({
      url: '/pages/userOrder/judge/judge?orderNo=' + orderNo + "&yunId=" + yunId + "&openId=" + openId,
    })

    /**
         * 获取系统信息
         */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          hiddenLoading: true
        });
      }
    });
  },
  //onemore
  onemore: function (e) {
    var that = this;
    onemoreFlag = true;
    goodOrders = new Array();
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    orderNo = e.currentTarget.dataset.reforderno;
    //获取订单列表，拼接商品信息
    wx.request({
      url: apiHost + 'xcx/order/detail',
      data: {
        yunId: yunId,
        openId: openId,
        orderNo: orderNo
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        
        for (var i = 0; i < res.data.data.goods.length; i++) {
          var good = {
            spuId: res.data.data.goods[i].spuId,
            count: res.data.data.goods[i].count
          }
          goodOrders.push(good);
        }
        deliveryFee = res.data.data.deliveryFee;
        createTime = util.formatTime(new Date()).toString();
        json = JSON.stringify(goodOrders);
        //清空购物车，再添加购物车
        wx.request({
          url: apiHost + 'xcx/userShoppingCart/clear',
          data: {
            yunId: yunId,
            openId: openId
          },
          header: {
            'conttent-type': 'application-json'
          },
          success: function (res) {

          }
        })
        //添加购物车
        wx.request({
          url: apiHost + 'xcx/userShoppingCart/batchAdd',
          method: "POST",
          data: {
            yunId: yunId,
            openId: openId,
            shopVos: goodOrders
          },
          header: {
            'conttent-type': 'application-json'
          },
          success: function (res) {
            console.log("@@@@@@");
            console.log(goodOrders);
            console.log(res)
            app.globalData.selectCondition = onemoreFlag;
            //跳转到购物车页面
            wx.switchTab({
              url: '/pages/index/index',
              success: function () {
              },
            });
          }
        })

        /**
         * 获取系统信息
         */
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              hiddenLoading: true
            });
          }
        });
      }
    })
    
    
  },
  // 删除dingdan
  delOrder: function (event) {
    
    orderNo = event.currentTarget.dataset.reforderno;
    var that = this;
    that.setData({
      showModal: true,
      delOrderNo: orderNo
    })
  },
  // confirmOrder:function(e){
  //   this.setData({
  //     showConfirmArea:true
  //   })
  // },
  toDetail: function (event) {
    var flag = "list";
    orderNo = event.currentTarget.dataset.orderNo
    wx.redirectTo({
      url: '/pages/userOrder/orderDetail/orderDetail?orderNo=' + orderNo + "&yunId=" + yunId + "&openId=" + openId + "&flag=" + flag,
    })
  },
  cancel: function (event) {
    this.setData({
      showModal: false,
      showConfirmArea: false,
      showCancelArea: false
    })
  },
  confirmOrders: function (e) {
    
    cOrderNo = e.currentTarget.dataset.reforderno
    this.setData({
      showConfirmArea: true,
      cOrderNo: cOrderNo
    })
  },
  cancelOrder: function (e) {
    
    orderNo = e.currentTarget.dataset.reforderno;
    this.setData({
      showCancelArea: true,
      cancelNo: orderNo
    })
  },
  cancelO: function () {
    var that = this;
    that.setData({
      alertModel: false
    })
  },
  confirmCancel: function (e) {
    
    var that = this;
    alertMsg = new Array();
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });

    orderNo = e.currentTarget.dataset.cancelorderNo;
    wx.request({
      url: apiHost + 'xcx/order/cancel',
      data: {
        yunId: yunId,
        orderNo: orderNo,
        openId: openId,
        'type': '1'
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        // console.log(res);
        /**
         * 获取系统信息
         */
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              hiddenLoading: true
            });
          }
        });
        // console.log(res);
        if (res.data.code == "10000") {
          wx.showToast({
            title: '取消订单成功!',
            icon: 'success',
            duration: 2000
          })
          that.orderDetail();
        } else {
          alertMsg.push(res.data.msg);
          that.setData({
            alertModel: true,
            alertMsg: alertMsg
          })
        }
      }
    })
    that.setData({
      showCancelArea: false
    })

    /**
         * 获取系统信息
         */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          hiddenLoading: true
        });
      }
    });
  },
  confirmOrder: function (e) {
    
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    orderNo = e.currentTarget.dataset.orderNo;
    wx.request({
      url: apiHost + 'xcx/order/confirmReceipt',
      data: {
        yunId: yunId,
        orderNo: orderNo,
        openId: openId
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        // console.log(res);
        if (res.data.code == "10000") {
          // wx.showToast({
          //   title: '确认收货成功!',
          //   icon: 'success',
          //   duration: 2000
          // })
          // that.orderDetail();
          wx.navigateTo({
            url: '/pages/userOrder/judge/judge?orderNo=' + orderNo + "&yunId=" + yunId + "&openId=" + openId,
          })
        }
      }
    })
    this.setData({
      showConfirmArea: false
    })

    /**
         * 获取系统信息
         */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          hiddenLoading: true
        });
      }
    });
  },
  confirm: function (event) {
    // console.log(event);
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    var delorderNo = event.currentTarget.dataset.delorderno;
    wx.request({
      url: apiHost + 'xcx/order/del',
      data: {
        yunId: yunId,
        orderNo: delorderNo,
        openId: openId
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        // console.log(res);
        /**
         * 获取系统信息
         */
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              hiddenLoading: true
            });
          }
        });
        if (res.data.code == "10000") {
          wx.showToast({
            title: '删除成功!',
            icon: 'success',
            duration: 2000
          })
          // 跳转订单列表
          console.log("111111");
          that.orderDetail();
        }
        hiddenLoading: true
      }
    })
    this.setData({
      showConfirmArea: false,
      showModal: false
    })
  },
  searchOrder: function (event) {
    var that = this;
    var schOrderNo = event.detail.value;
    wx.request({
      url: apiHost + 'xcx/order/searchList',
      data: {
        yunId: yunId,
        openId: openId,
        start: start,
        length: length,
        sign: sign,
        orderNo: schOrderNo
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        that.setData({
          detailList: res.data.data
        })
      }
    })
  },
  orderDetail: function () {
    var that = this;
    // console.log("yunId="+yunId+"openId="+openId+"sign="+sign+"start="+start+"&length="+length)
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    wx.request({
      url: apiHost + 'xcx/order/searchList',
      data: {
        yunId: yunId,
        openId: openId,
        start: start,
        length: length,
        sign: sign
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {
        console.log("orderlist is");
        console.log(res);
        if(res.data.code == "10000"){
          list = res.data.data.list;
          limitTime = res.data.data.limitTime;
        }else{
          if(openId == ''){
            alertMsg.push(res.data.msg);
            that.setData({
              alertModel: true,
              alertMsg: alertMsg
            })
            wx.navigateTo({
              url: '../../login/login?openId=' + openId,
              success: function () {
                wx.hideLoading();   //隐藏加载loading
              },
            });
          }else{
            alertMsg.push(res.data.msg);
            that.setData({
              alertModel: true,
              alertMsg: alertMsg
            })
          }
        }
        // deliveryLimitTime = res.data.data.deliveryLimitTime;

        phone = res.data.data.phone;
        // console.log(limitTime);
        that.setData({
          detailList: res.data.data,
          phone: res.data.data.phone,
          // deliveryLimitTime: deliveryLimitTime

        })
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //验证码倒计时函数

  getCode: function (options) {

    var that = this;

    var currentTime = that.data.currentTime;

    that.setData({

      time: currentTime + '秒'

    })

    interval = setInterval(function () {

      that.setData({

        time: (currentTime - 1) +
        '秒'

      })

      currentTime--;

      if (currentTime <=
        0) {

        clearInterval(interval)

        that.setData({

          time: '重新获取',

          currentTime: 60,

          disabled: false

        })

      }

    }, 1000)

  },
  goindex:function(event){
    wx.switchTab({
      url: '/pages/Zindex/Zindex',
      success: function () {
      },
    });
  }
})